// pages/song/song.js

const innerAudioContext = wx.createInnerAudioContext();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    title: '',
    songData: '',
    mid: '', //音乐的id
    songUrl: '', //
    state: true,//音乐的状态 true 表示正在播放 false 表示暂停播放
    animation: {},
    list_index: 0,
    playList: [],
  },
  //根据id获取歌曲信息
  getSongData(id) {
    var reqTask = wx.request({
      url: 'http://musicapi.leanapp.cn/song/detail',
      data: { ids: id },
      header: { 'content-type': 'application/json' },
      method: 'GET',
      dataType: 'json',
      responseType: 'text',
      success: (result) => {
        if (result.data.code == 200) {
          this.setData({
            songData: result.data.songs[0],
            title: result.data.songs[0].name,
            songUrl: 'https://music.163.com/song/media/outer/url?id=' + id //直接进行歌曲播放
          })
        }
        this.saveSongData(this.data.songData)
        this.changeTitle(this.data.title)
        this.listPlay();
      }
    });
  },
  //将当前歌曲的信息保存
  saveSongData(data) {
    console.log(data)
    if(data){
      let songData = {
        picUrl: data.al.picUrl,
        name: data.name,
        name_tro: data.alia,
        id: data.id,
        songUrl: 'https://music.163.com/song/media/outer/url?id=' + data.id
      } 
      wx.setStorageSync("song", songData);
      let currentPages =  getCurrentPages();
      if(currentPages.length > 1){
        let perPage = currentPages[currentPages.length-2];
        perPage.selectComponent("#music").setData({song:songData})
        if(currentPages.length > 2){
          let perPage = currentPages[currentPages.length-3];
          perPage.selectComponent("#music").setData({song:songData})
        }
      }
    }
    
  },
  changeTitle(title) {
    wx.setNavigationBarTitle({
      title: title
    });

  },
  getSongUrl(id) {
    wx.request({
      url: 'http://musicapi.leanapp.cn/song/url',
      data: { id: id },
      header: { 'content-type': 'application/json' },
      method: 'GET',
      dataType: 'json',
      responseType: 'text',
      success: (result) => {
        if (result.data.code == 200) {
          console.log(result.data)
        }
      }
    })
  },
  play() {
    this.setData({
      state: true
    })
    innerAudioContext.play()
  },
  pause() {
    this.setData({
      state: false
    })
    innerAudioContext.pause()
  },
  prev(){
    let index = this.data.list_index;
    let list = this.data.playList;
    if(index == 0){
      this.setData({
        list_index:0
      })
      index = 0;
    }
    else{
      index--
    }
    let song = list[index];
    this.loadEvent(song.id)
  },
  //下一首，当该歌曲为最后一首时，重列表头开始
  next() {
    let index = this.data.list_index;
    let list = this.data.playList;
    if(index == list.length-1){
      this.setData({
        list_index:0
      })
      index = 0;
    }
    else{
      index++
    }
    let song = list[index];
    this.loadEvent(song.id)
  },
  liebiao(){
    wx.removeStorageSync('allPlay');
    this.setData({
      playList:[],
      list_index:0,
    })
    this.loadEvent(this.data.mid)
  },
  //播放列表
  listPlay() {
    let allPlay = wx.getStorageSync("allPlay");
    if(allPlay){
      this.setData({
        playList: allPlay
      })
      let i = this.getListIndex();
      if(i == -1){
        this.addNewSongToList();
      }
    }else{
      this.addNewSongToList()
    }
   
  },
  //当前歌曲在列表的位置 ,返回值-1为不在原列表
  getListIndex() {
    let id = this.data.mid;
    let data = this.data.playList;
    for (let i in data) {
      if (id == data[i].id) {
        this.setData({
          list_index: i
        })
        return i;
      }
    }
    return -1;
  },
  //播放的歌曲不在列表当中，将歌曲添加至列表首部
  addNewSongToList() {
    let songs = this.data.songData;
    let allSongs = this.data.playList;
    console.log(songs)
    console.log(allSongs)
    let data = {
      id: songs.id,
      name: songs.name,
      nama_tro: songs.alia[0],
    }

    allSongs.unshift(data)
    this.setData({
      playList:allSongs
    })
    wx.setStorageSync("allPlay", allSongs);
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.loadEvent(options.mid)

  },
  //将onLoad中的放入loadEvent
  loadEvent(id){
    this.setData({
      mid: id
    })
    if (id) {
      this.getSongData(id)
      
      console.log(this.data)
      innerAudioContext.autoplay = true;
      innerAudioContext.src = 'https://music.163.com/song/media/outer/url?id='+id;
      innerAudioContext.onPlay(() => {
        this.saveSongData(this.data.songData)
        console.log('开始播放')
      })

      innerAudioContext.onError((res) => {
        console.log(res.errMsg)
        console.log(res.errCode)
      })
      innerAudioContext.onEnded(() => {
        this.next();
      });
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let animation = wx.createAnimation({
      duration: 400,
      timingFunction: 'linear',
      delay: 0,
      transformOrigin: '50% 50% 0'
    });
    this.animation = animation;
    animation.rotate(180).step();
    this.setData({
      animation: this.animation.export()
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})